﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using DailyDiet.Models;
using DailyDiet.Services;
using DailyDiet.Services.Impl;
using DailyDiet.Services.Navigation;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using SQLite;

namespace DailyDiet.ViewModels
{
    /// <summary>
    /// 自定义页面的ViewModel
    /// </summary>
    public class SelfDefinePageViewModel : ViewModelBase
    {
        /******** 构造函数 ********/

        /// <summary>
        /// 菜品存储service
        /// </summary>
        private IDietStorageService _dietStorageService;

        /// <summary>
        /// 偏好存储service
        /// </summary>
        private IPreferenceStorage _preferenceStorage;

        private ISplitSentenceService _splitSentenceService;

        public SelfDefinePageViewModel(
            IDietStorageService dietStorageService, 
            IPreferenceStorage preferenceStorage,
            ISplitSentenceService splitSentenceService)
        {
            _dietStorageService = dietStorageService;
            _preferenceStorage = preferenceStorage;
            _splitSentenceService = splitSentenceService;
        }

        //******** 绑定属性 ********/

        /// <summary>
        /// 搜索关键词,由上一个页面导航传入
        /// </summary>
        public string SearchKey {

            get => _searchKey;
            set => Set(nameof(SearchKey), ref _searchKey, value);
        }

        private string _searchKey;

        /// <summary>
        /// 菜品集合-->用于展示搜索结果
        /// </summary>
        public List<Diet> DietsList
        {
            get => _dietsList;
            set => Set(nameof(DietsList), ref _dietsList, value);
        }

        private List<Diet> _dietsList;
        

        /******** 绑定命令 ********/

        /// <summary>
        /// 展示搜索结果-->根据关键字进行模糊查询
        /// </summary>
        private RelayCommand _appearingCommand;
        public RelayCommand AppearingCommand =>
            _appearingCommand ?? (_appearingCommand = new RelayCommand(async () => await AppearingCommandFunc()));

        public async Task AppearingCommandFunc() {

            List<string> words = _splitSentenceService.SplitSentenceToWords(SearchKey);
            
            words.Add(SearchKey);
            List<Diet> searchResult = new List<Diet>();
            foreach (var word in words) {
                Expression<Func<Diet, bool>> searchByNameWhere = p =>
                    p.Name.Contains(word);
                searchResult.AddRange(await _dietStorageService.GetAllDietsAsync(searchByNameWhere));
            }

            searchResult.Distinct();
            DietsList = searchResult;
        }

    }
}
